<template>
  <div>
    <el-card class="box-card">
      <mytitle :showLine="false">{{ $route.meta.title }}</mytitle>
      <div class="contain">
        <div class="tree-box">
          <el-tabs v-model="activetTabs" type="card" @tab-click="handleClick">
            <el-tab-pane label="部门组织" name="powerInfo">
              <el-tree :data="options" :props="defaultProps" default-expand-all :expand-on-click-node="false"
                @node-click="handleNodeClick" accordion></el-tree>
            </el-tab-pane>
            <el-tab-pane label="部门人员" name="userInfo">
              <el-input style="width: 200px;margin-left: 20px;" placeholder="搜索姓名" 
              @input="nameChange"
                prefix-icon="el-icon-search" v-model="memberInfo.name">
              </el-input>
              <div class="member-box">
                <div v-for="item in memberData" :key="item.userId" class="member-item"
                  :class="userInfo.userId == item.userId ? 'active-member' : ''" @click="checkedItem(item)">
                  <div class="head">{{ item.name[0] }}</div>
                  <div class="name">{{ item.name }}</div>
                  <div class="phone">{{ item.phone }}</div>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div class="check-box">      
          <div style="display: flex;align-items: center;gap:20px;">
            <div class="names">{{ activetTabs == 'userInfo' ? userInfo.name : powerInfo.name }}</div>
          <el-button  v-if="powerInfo.name&&activetTabs == 'powerInfo'" type="success"  @click="editdepartment">部门编辑</el-button>
        </div>
          <el-checkbox-group v-loading="loading" v-model="info.resourceIdS">
            <mytitle :showLine="false">系统权限</mytitle>
            <div class="check-boxs">
              <div  class="check-item" v-for="item in  allPowerlist.systemResource"  :key="item.id">
              <el-checkbox :label="item.id" border>{{ item.title
             }}</el-checkbox>
             </div>
            </div>
            
            
            <mytitle :showLine="false">功能权限</mytitle>
            <div class="check-boxs">
              <div  class="check-item" v-for="item in  allPowerlist.functionResource"  :key="item.id">
              <el-checkbox :label="item.id" border>{{ item.title
             }}</el-checkbox>
             </div>
            </div>
          </el-checkbox-group>
          <div class="sureBth" v-if="userInfo.name || powerInfo.name">
            <el-button type="success"  style="margin: 20px;" @click="reset()" plain>重置</el-button>
            <el-button type="success"  style="margin: 20px;" @click="addFarm">确定</el-button>
          </div>
        </div>
      </div>
      <el-dialog title="部门编辑" :visible.sync="editDig" width="30%">
        <el-form :model="editInfo" >
          <el-form-item label="部门原名称" label-width="120px" prop="">
            <el-input disabled v-model="editInfo.oldName"  autocomplete="off" style="width: 200px;"></el-input>
          </el-form-item>
          <el-form-item label="部门新名称" label-width="120px">
            <el-input v-model="editInfo.name"  autocomplete="off" style="width: 200px;"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="editDig = false" >取 消</el-button>
          <el-button type="success"  @click="sureEdit">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import { findUserdataByDepartmentId, findPcAccountByCondition, findResourceByDepartmentIdAndUserId, giveDepartmentAndUserAddResource,addDepartment } from "../util/api.js"
export default {
  data() {
    return {
      options: [],
      loading: false,
      editDig:false,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      activetTabs: "powerInfo",
      allPowerlist: {},
      userInfo: {
        userId: "",
        name: ""
      },
      powerInfo: {
        departmentId: "",
        name: ""
      },
      editInfo:{
        oldName:"",
        name:"",
        id:""
      },
      mydepartmentIdS: {},//复制一份子部门
      memberInfo: {
        name: ""
      },
      memberData: [],
      activeInfo: {},
      info: {
        resourceIdS: [],
        pcUserId: "",
        departmentIdS: {
          departmentId:"",
          departmentParentId:[]
        }
      },
    }
  },
  mounted() {
    this.getDepart()
    this.getAllpower()
  },
  methods: {
    //所有部门
    async getDepart() {
      let res = await findUserdataByDepartmentId({ departmentId: "1223456852" })
      // console.log(res)
      if (res.code != 200) return this.options = []
      this.options = res.data
    },
    //所有员工
    async getMembers() {
      let res = await findPcAccountByCondition(this.memberInfo)
      // console.log(res)
      if (res.code != 200) return
      this.memberData = res.data.rows
    },
    //员工搜索
    nameChange(){
          this.debounce(this.getMembers(),1000)
    },
    //获取权限
    async getAllpower() {
      this.loading = true
      let data = this[`${this.activetTabs}`]
      let res = await findResourceByDepartmentIdAndUserId(data)
      // console.log(res)
      if (res.code != 200) return
      if (this.powerInfo.name || this.userInfo.name) {
        // console.log(res)
        if (res.data.systemResource.length > 0) {
          let arraysystem = res.data.systemResource.map(v => {
            return v.id
          });
          this.info.resourceIdS = this.info.resourceIdS.concat(arraysystem)
        }
        if (res.data.functionResource.length > 0) {
          let array = res.data.functionResource.map(v => {
            return v.id
          });
          this.info.resourceIdS = this.info.resourceIdS.concat(array)
        }
        this.copyPower = JSON.parse(JSON.stringify(this.info.resourceIdS))//拷贝一份原始数据
      } else {
        this.allPowerlist = res.data
      }
      this.loading = false
    },
    //部门点击
    handleNodeClick(data) {
      this.info.resourceIdS = [] //清空已经选择
      this.info.departmentIdS = {
          departmentId:"",
          departmentParentId:[]
        } //清楚上一个点击部门
      this.info.departmentIdS.departmentId = data.id
      this.info.departmentIdS.departmentParentId.push(data.id)
      if (data.children != null) {
        this.getChildrenID(data)//添加子集部门id
      }
      this.powerInfo.name = data.name
      this.powerInfo.departmentId = data.id
      this.mydepartmentIdS = JSON.stringify(this.info.departmentIdS)
      this.getAllpower()

    },
    //点击编辑部门
    editdepartment(){
        //  console.log(this.powerInfo)
         this.editInfo.oldName = this.powerInfo.name
         this.editInfo.id = this.powerInfo.departmentId
         this.editDig = true
    },
    //确认修改
   async sureEdit(){
       if(!this.editInfo.name)return this.$message.error('请填入新名称')
       let res = await addDepartment(this.editInfo)  
        if(res.code!=200)return this.$message.error(res.msg)
        this.$message.success('修改成功')
        this.editDig = false
        this.getDepart()
    },
    //递归铺平
    getChildrenID(obj) {
      obj.children.forEach(v => {
        this.info.departmentIdS.departmentParentId.push(v.id)
        if (v.children != null) {
          this.getChildrenID(v)
        }
      });
    },
    //防抖
    debounce(func, wait, immediate) {
        //定时器变量
        var timeout;
        return function () {
            //每次触发scrolle，先清除定时器
            clearTimeout(timeout);
            //指定多少秒后触发事件操作handler
            timeout = setTimeout(func, wait);
        };
    },
    //员工点击
    checkedItem(item) {
      this.info.resourceIdS = []
      this.info.pcUserId = item.userId;
      this.userInfo.userId = item.userId;
      this.userInfo.name = item.name;
      this.getAllpower()
    },
    // 部门与员工切换
    handleClick(val) {
      this.info.resourceIdS = []
      if (this.activetTabs == 'userInfo') {
        this.getMembers()
        this.info.pcUserId = JSON.parse(JSON.stringify(this.userInfo.userId)) 
        this.info.departmentIdS = {
          departmentId:"",
          departmentParentId:[]
        }
      } else {
        this.info.departmentIdS = JSON.parse(this.mydepartmentIdS)
        this.info.pcUserId = ""
      }
      this.getAllpower()
    },
    //重置
    reset() {
      this.info.resourceIdS = JSON.parse(JSON.stringify(this.copyPower))
    },
    //确认修改
    addFarm() {
      this.$confirm('确认修改?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // console.log(this.info)
        let res = await giveDepartmentAndUserAddResource(this.info)
        if(res.code!=200)return this.$message.error(res.msg)
        this.$confirm('修改成功!, 是否重新登录?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'success'
        }).then(() => {
          this.$message({
						type: "success",
						message: "已退出!",
					});
          sessionStorage.clear()
					this.$router.push({ path: '/' })
					location.reload();
        })
      })
    }
  }
}
</script>
<style lang="less" scoped>
.box-card {
  width: 100%;
  margin: 14px 0;

  .contain {
    width: 100%;
    display: flex;
    gap: 20px;

    .tree-box {
      background: #F8F7FC;
      min-height: 200px;
      width: 300px;
      // padding: 20px;
      display: flex;
      justify-content: left;
      box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);

      /deep/.el-tree {
        background-color: #F8F7FC;
        font-size: 16px;
        color: #01B780;
      }

      /deep/.el-tree-node__label {
        background-color: #F8F7FC;
        font-size: 16px !important;
        color: black;
      }

      /deep/.el-tree-node__expand-icon {
        font-size: 16px !important;
        color: #01B780;
      }

      /deep/.is-current .el-tree-node__label {
        color: #01B780 !important;
      }

      .el-tabs {
        width: 100%;
      }

      .member-box {
        width: 100%;
        margin-top: 20px;
        overflow-y: auto;
        max-height: 500px;

        .member-item {
          width: 95%;
          display: flex;
          background-color: #ffffff;
          border-radius: 15px;
          justify-content: space-between;
          align-items: center;
          padding: 5px;
          color: #01B780;
          margin: 5px auto;
          box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
          cursor: pointer;

          .head {
            width: 30px;
            line-height: 30px;
            border-radius: 50%;
            background-color: #01B780;
            height: 30px;
            text-align: center;
            color: #ffffff;
          }
        }

        .active-member {
          color: #ffffff;
          background-color: #01B780;

          .head {
            background-color: #ffffff;
            color: #01B780;
          }
        }
      }
    }

    .check-box {
      flex: 1;
      background: #F8F7FC;
      min-height: 200px;
      min-width: 300px;
      padding: 20px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);

      .names {
        color: #01B780;
        font-size: 22px;
        height: 30px;
        line-height: 22px;
      }
      .check-boxs{
             display: flex;
             gap: 20px 10px;
             flex-wrap: wrap;
             margin-bottom: 20px;
             .check-item{
               min-width: 170px;
             }
      }
      .sureBth {
        margin: 20px 0;
      }

      /deep/.is-bordered {
        margin-left: 0 !important;
      }
    }
  }
}

/deep/.el-tabs__item.is-active {
  color: #52B484 !important;
}

/deep/.el-tabs__item:hover {
  color: #52B484 !important;
  cursor: pointer;
}

/deep/.el-tabs__item {
  color: #3A3D3D !important;
}
/deep/.is-checked .el-checkbox__inner{
   background-color: #67C23A;
   border-color: #67C23A;
}
/deep/.is-checked .el-checkbox__label{
   color: #6F7174;
}
/deep/.el-checkbox.is-bordered.is-checked{
  border-color: #01B780;
}</style>